
package com.huizhan.web.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.*;
import io.swagger.annotations.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.huizhan.web.view.*;
import com.huizhan.web.common.utils.ExcelUtil;
import com.huizhan.web.dao.*;
import com.huizhan.web.model.*;

/**
 * 人api
 */
 
@Api(tags = "Personal",description = "人")
@RestController
public class PersonalController {
    
    @Autowired
    private PersonalDao dao;
   
    @Autowired
    private RegisterDao jdao;
   
    @Autowired
    private SourceDao sdao;

    @Autowired
    private DocumentTypeDao ddao;

    @Autowired
    private DocumentDao Ddao;
    
    @Autowired
    private ProjectDao projectDao;

    /**
     * 获取人集合
     * @return api结果
     */
    @ApiOperation(value = "根据条件获取人")
    @RequestMapping(value =  "/api/Personal/{type}/{projectId}/{phone}/",method = {RequestMethod.GET})
    public ApiResult<Personal> Get(@PathVariable Integer type,@PathVariable String projectId,@PathVariable String phone){
         ApiResult<Personal> result=new ApiResult<Personal>();
        try 
        {
            Personal personal=dao.findByProjectIdAndTypeAndPhone(projectId,type,phone);

            result.setData(personal);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 根据ID获取人信息
     * @param id 人ID
     * @return api结果
     */
    @ApiOperation(value = "根据ID获取人信息")
    @RequestMapping(value =  "/api/Personal/{id}",method = {RequestMethod.GET})
    public ApiResult<Personal> Get(@PathVariable String id){
        ApiResult<Personal> result=new ApiResult<Personal>();
        try
        {
            Personal model= dao.getOne(id);
            result.setData(model);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 修改人信息
     * @param id 人ID
     * @param model 人信息
     * @return api结果
     */
    @ApiOperation(value = "修改人信息")
    @RequestMapping(value =  "/api/Personal/{id}",method = {RequestMethod.PUT})
    public ApiResult<Personal> Edit(@PathVariable String id,@RequestBody Personal model){
        ApiResult<Personal> result=new ApiResult<Personal>();
        try
        {
            Project project=projectDao.getOne(model.getProjectId());
            Register register=jdao.getOne(model.getRegisterId());
            Personal personal=dao.getOne(id);

            if(register==null){
                result.setHasError(true);
                result.setMessage("注册通道ID不能为空");
            }else if(personal==null){
                result.setHasError(true);
                result.setMessage("参数错误");
            }else if(!personal.getRegisterId().equals(register.getRegisterId())){
                result.setHasError(true);
                result.setMessage("注册通道ID不能更改");
            }else{
                if(model.getVerify()==1&&personal.getVerify()==0){
                    if(model.getVerify()==1){
                        try{
                            if(register.getEmail()!=null&&register.getEmail().length()>0&&model.getEmail()!=null&&model.getEmail().length()>0){
                                EmailUtil.sendMail(model.getEmail(), register.getName(), register.getEmail());
                            }else if(register.getSms()!=null&&register.getSms().length()>0&&model.getPhone()!=null&&model.getPhone().length()>0){
                                
                                String data="{\"account\":\"dh81653\",\"password\":\""+
                                TenpayUtil.MD5("e3YiG73c").toLowerCase()
                                +"\",\"msgid\":\""
                                +(UUID.randomUUID().toString())
                                +"\",\"phones\":"
                                +model.getPhone()
                                +",\"content\":\""
                                +register.getSms();
                                data+="\",\"sign\":\"【"
                                +project.getSignName()
                                +"】\",\"subcode\":\"\",\"sendtime\":\"\"}";

                                TenpayHttpClient httpClient = new TenpayHttpClient();  

                                httpClient.callHttpPost("http://www.dh3t.com/json/sms/Submit", data);
                                String  resContent = httpClient.getResContent();
                            }
                        }catch (Exception e){

                        }
                    }
                }

                personal.setName(model.getName());
                personal.setCompany(model.getCompany());
                personal.setAddress(model.getAddress());
                personal.setArea(model.getArea());
                personal.setSex(model.getSex());
                personal.setAvatar(model.getAvatar());
                personal.setEmail(model.getEmail());
                personal.setPosition(model.getPosition());
                personal.setBooth(model.getBooth());
                personal.setIdCard(model.getIdCard());
                personal.setVerify(model.getVerify());
                personal.setDisabled(model.getDisabled());
                dao.save(personal);
                result.setData(personal);
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 添加人信息
     * @param model 人信息
     * @return api结果
     */
    @ApiOperation(value = "批量添加人信息")
    @RequestMapping(value =  "/api/Personal/{id}",method = {RequestMethod.PATCH})
    public ApiResult<List<Personal>> Add(@PathVariable Long id, @RequestBody List<Personal> list){
         ApiResult<List<Personal>> result=new ApiResult<List<Personal>>();
        try
        {
            Register register=jdao.getOne(id);

            if(register==null){
                result.setHasError(true);
                result.setMessage("注册不能为空");
            }else{
                Project project=projectDao.getOne(register.getProjectId());
                if(project==null){
                    result.setHasError(true);
                    result.setMessage("注册不能为空");
                }else{
                    if(register.getDocumentTypeId()==null){
                        
                        DocumentType type=new DocumentType();
            
                        type.setCreateDate(new Date());
                        type.setProjectId(register.getProjectId());
                        type.setName(register.getName());
                        
                        ddao.save(type);
                        
                        register.setDocumentTypeId(type.getDocumentTypeId());

                        jdao.save(register);
                    }

                    List<Integer> vs=new ArrayList<Integer>();
                    List<Source> source = sdao.findByRegisterId(id);
                    List<Personal> ls=new ArrayList<Personal>();
                    List<Document> ds=new ArrayList<Document>();

                    for (Personal model : list) {
                        model.setRegisterId(register.getRegisterId());
                        model.setType(register.getType());
                        model.setProjectId(register.getProjectId());
                        if(dao.findByProjectIdAndTypeAndPhone(model.getProjectId(),model.getType(),model.getPhone())!=null){
                            result.setMessage(model.getPhone()+"手机号码已存在"+(result.getMessage()==null?"":"\n"+result.getMessage()));
                        }else{
                            if(model.getCode()==null||model.getCode()==""){
                                String no=TenpayUtil.randomNumber(8);
                                int a=Integer.parseInt(no);
                                while(vs.contains(a)||dao.countByProjectIdAndCode(model.getProjectId(), no)>0){
                                    no=TenpayUtil.randomNumber(8);
                                }
                                vs.add(a);
                                model.setCode(no);
                            }
                            if(model.getOpenId()!=null&&model.getOpenId().length()>0){
                                for (Source source2 : source) {
                                    if(source2.getName().equals(model.getOpenId())){
                                        model.setSourceId(model.getSourceId());
                                        break;
                                    }
                                }
                                model.setOpenId("");
                            }
                            if(model.getAvatar()!=null&&model.getAvatar().length()>0){
                                model.setVerify(model.getAvatar().equals("是")?1:0);
                                model.setAvatar("");
                            }else{
                                model.setVerify(register.getVerify()==1?0:1);
                            }
                            model.setPersonalId(UUID.randomUUID().toString());
                            model.setCreateDate(new Date());
                            model.setIsSign(0);
                            model.setIsPassage(0);
                            model.setDisabled(0);
                            ls.add(model);

                            Document document=new Document();

                            document.setCode(model.getCode());
                            document.setDocumentTypeId(register.getDocumentTypeId());
                            document.setName(model.getName());
                            document.setAvatar(model.getAvatar());
                            document.setIdNumber(model.getPhone());
                            document.setProjectId(register.getProjectId());
                            document.setTypeName(register.getName());
                            
                            ds.add(document);

                            if(model.getVerify()==1){
                                try{
                                    if(register.getEmail()!=null&&register.getEmail().length()>0&&model.getEmail()!=null&&model.getEmail().length()>0){
                                        EmailUtil.sendMail(model.getEmail(), register.getName(), register.getEmail());
                                    }else if(register.getSms()!=null&&register.getSms().length()>0&&model.getPhone()!=null&&model.getPhone().length()>0){
                                        
                                        String data="{\"account\":\"dh81653\",\"password\":\""+
                                        TenpayUtil.MD5("e3YiG73c").toLowerCase()
                                        +"\",\"msgid\":\""
                                        +(UUID.randomUUID().toString())
                                        +"\",\"phones\":"
                                        +model.getPhone()
                                        +",\"content\":\""
                                        +register.getSms();
                                        data+="\",\"sign\":\"【"
                                        +project.getSignName()
                                        +"】\",\"subcode\":\"\",\"sendtime\":\"\"}";
        
                                        TenpayHttpClient httpClient = new TenpayHttpClient();  
        
                                        httpClient.callHttpPost("http://www.dh3t.com/json/sms/Submit", data);
                                        String  resContent = httpClient.getResContent();
                                    }
                                }catch (Exception e){
        
                                }
                            }

                        }
                    }
                    
                    Ddao.saveAll(ds);
                    dao.saveAll(ls);
                    result.setData(ls);
                }
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }


    /**
     * 添加人信息
     * @param model 人信息
     * @return api结果
     */
    @ApiOperation(value = "添加人信息")
    @RequestMapping(value =  "/api/Personal/",method = {RequestMethod.POST})
    public ApiResult<Personal> Add(@RequestBody Personal model, HttpServletRequest request){
         ApiResult<Personal> result=new ApiResult<Personal>();
        try
        {
            Project project=projectDao.getOne(model.getProjectId());
            Register register=jdao.getOne(model.getRegisterId());

            if(project==null){
                result.setHasError(true);
                result.setMessage("注册不能为空");
            }else if(register==null){
                result.setHasError(true);
                result.setMessage("注册不能为空");
            }else if(model.getProjectId()==""){
                result.setHasError(true);
                result.setMessage("项目ID不能为空");
            }else if(dao.findByProjectIdAndTypeAndPhone(model.getProjectId(),model.getType(),model.getPhone())!=null){
                result.setHasError(true);
                result.setMessage("手机号码已存在");
            }else{
                if(register.getDocumentTypeId()==null){
                    DocumentType type=new DocumentType();
        
                    type.setCreateDate(new Date());
                    type.setProjectId(register.getProjectId());
                    type.setName(register.getName());
                    
                    ddao.save(type);
                    
                    register.setDocumentTypeId(type.getDocumentTypeId());

                    jdao.save(register);
                }
                String no=TenpayUtil.randomNumber(8);
                while(dao.countByProjectIdAndCode(model.getProjectId(), no)>0){
                    no=TenpayUtil.randomNumber(8);
                }
                Optional<Source> source = sdao.findById(model.getSourceId());
                if(source.isPresent()){
                    source.get().setHit(source.get().getHit()+1);
                    source.get().setPerson(source.get().getPerson()+1);
                    sdao.save(source.get());
                }
                model.setCode(no);
                model.setPersonalId(UUID.randomUUID().toString());
                model.setCreateDate(new Date());
                model.setIsSign(0);
                model.setIsPassage(0);
                model.setDisabled(0);
                model.setVerify(register.getVerify()==1?0:1);
                dao.save(model);
                result.setData(model);
                
                Document document=new Document();

                document.setCode(model.getCode());
                document.setDocumentTypeId(register.getDocumentTypeId());
                document.setName(model.getName());
                document.setAvatar(model.getAvatar());
                document.setIdNumber(model.getPhone());
                document.setProjectId(register.getProjectId());
                document.setTypeName(register.getName());
                
                Ddao.save(document);
                
                if(model.getVerify()==1){
                    try{
                        if(register.getEmail()!=null&&register.getEmail().length()>0&&model.getEmail()!=null&&model.getEmail().length()>0){
                            EmailUtil.sendMail(model.getEmail(), register.getName(), register.getEmail());
                        }else if(register.getSms()!=null&&register.getSms().length()>0&&model.getPhone()!=null&&model.getPhone().length()>0){
                            
                            String data="{\"account\":\"dh81653\",\"password\":\""+
                            TenpayUtil.MD5("e3YiG73c").toLowerCase()
                            +"\",\"msgid\":\""
                            +(UUID.randomUUID().toString())
                            +"\",\"phones\":"
                            +model.getPhone()
                            +",\"content\":\""
                            +register.getSms();
                            data+="\",\"sign\":\"【"
                            +project.getSignName()
                            +"】\",\"subcode\":\"\",\"sendtime\":\"\"}";

                            TenpayHttpClient httpClient = new TenpayHttpClient();  

                            httpClient.callHttpPost("http://www.dh3t.com/json/sms/Submit", data);
                            String  resContent = httpClient.getResContent();
                        }
                    }catch (Exception e){

                    }
                }
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    
    /**
     * 查询人员分页
     * @param model 账号人员信息
     * @return api结果
     */
    @ApiOperation(value = "查询观众分页")
    @RequestMapping(value =  "/api/Personal/Search",method = {RequestMethod.POST})
    public ApiResult<List<Personal>> Search(@RequestBody PagePersonal model){
         ApiResult<List<Personal>> result=new ApiResult<List<Personal>>();
         
        try
        {     
            Long start=model.getStartDate().getTime()/1000;
            Long end=model.getEndDate().getTime()/1000;

            PageRequest pageable = PageRequest.of(model.getPageIndex(),model.getPageSize(),Direction.DESC,"personal_Id") ;            
            Page<Personal> page = dao.findByWhere(model.getName(),model.getPhone(),model.getProjectId(),model.getCode(),start,end,model.getType(),model.getRegisterId(),pageable);
            result.setData(page.getContent());
            result.setTotal(page.getTotalElements());
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    /**
     * 查询人员分页
     * @param model 账号人员信息
     * @return api结果
     */
    @ApiOperation(value = "导出观众分页")
    @ResponseBody
    @RequestMapping(value =  "/api/Personal/Export",method = {RequestMethod.POST})
    public void Export(@RequestBody PagePersonal model, HttpServletResponse response){
         
        try
        {     
            Long start=model.getStartDate().getTime()/1000;
            Long end=model.getEndDate().getTime()/1000;

            PageRequest pageable = PageRequest.of(model.getPageIndex(),model.getPageSize(),Direction.DESC,"personal_Id") ;            
            Page<Personal> page = dao.findByWhere(model.getName(),model.getPhone(),model.getProjectId(),model.getCode(),start,end,model.getType(),model.getRegisterId(),pageable);
            List<Personal> list=page.getContent();

            ExcelUtil.<Personal>exportExcel("人员",list, Personal.class, response);
            
        }catch(Exception e){
           String str= e.getMessage();
        }
    }

    /**
     * 删除人信息
     * @param id 人ID
     * @return api结果
     */
    @ApiOperation(value = "删除人信息")
    @RequestMapping(value =  "/api/Personal/{id}",method = {RequestMethod.DELETE})
    public ApiResult<Object> Delete(@PathVariable  String id){
        ApiResult<Object> result=new ApiResult<Object>();
        try 
        {
            dao.deleteById(id);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}

